/*
 * Powered By [lixin]
 * 代码脚手架工具生成 [AI-Code]
 */

package com.rzhkj.box.service.impl;

import com.baidu.fsg.uid.UidGenerator;
import com.rzhkj.box.dao.BoxDAO;
import com.rzhkj.box.entity.Box;
import com.rzhkj.box.entity.BoxStateEnum;
import com.rzhkj.box.service.BoxSV;
import com.rzhkj.core.base.BaseMybatisDAO;
import com.rzhkj.core.base.BaseMybatisSVImpl;
import com.rzhkj.core.enums.YNEnum;
import com.rzhkj.core.exceptions.BaseException;
import com.rzhkj.core.exceptions.BoxException;
import com.rzhkj.core.tools.Md5;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


@Component
@Service
public class BoxSVImpl extends BaseMybatisSVImpl<Box, Long> implements BoxSV {

    @Resource
    private BoxDAO boxDAO;

    @Resource
    private UidGenerator uidGenerator;

    @Override
    protected BaseMybatisDAO getBaseMybatisDAO() {
        return boxDAO;
    }

    @Override
    public void save(Box entity) throws BaseException {
        Map<String, Object> param = new HashMap<>();
        param.put("namespace", entity.getNamespace());
        param.put("name", entity.getName());
        Box box = boxDAO.load(param);
        if (box != null) {
            throw new BoxException(BaseException.BaseExceptionEnum.Exists);
        }
        entity.setMinLimit(entity.getMinLimit() > 0 ? entity.getMinLimit() : Box.BoxLimit.MinLimit.val);
        entity.setMaxLimit(entity.getMaxLimit() > 0 ? entity.getMaxLimit() : Box.BoxLimit.MaxLimit.val);
        entity.setIsCache(entity.getIsCache() != null ? YNEnum.Y.name() : YNEnum.N.name());
        entity.setCode(String.valueOf(uidGenerator.getUID()));
        entity.setApiKey(UUID.randomUUID().toString());
        entity.setApiSecret(Md5.md5(entity.getApiKey()));
        entity.setState(BoxStateEnum.Enable.name());
        entity.setCreateTime(new Date());
        entity.setUpdateTime(new Date());
        super.save(entity);
    }

    /**
     * 加载对象Box 通过code
     *
     * @param code 编码
     * @return Box
     */
    @Override
    public Box loadByCode(java.lang.String code) {
        return boxDAO.loadByCode(code);
    }

    /**
     * 删除对象Box
     *
     * @param id id* @param code 编码
     * @return Box
     */
    @Override
    public void delete(java.lang.Long id, java.lang.String code) {
        boxDAO.delete(id, code);
    }


}
